package com.iqiyi.dbagent.base.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import javax.sql.DataSource;

import com.iqiyi.dbagent.base.config.i.Configuration;
import com.iqiyi.dbagent.base.i.IInitDataBase;

/**
 * @Title: DefaultInitDataBaseImpl.java
 * @Package com.iqiyi.dbagent.base.impl
 * @Description: 默认数据库初始化工具
 * @author wangnianming
 * @date 2015年12月16日 下午3:45:17
 * @version V1.0
 */
public class DefaultInitDataBaseImpl implements IInitDataBase{

    private Configuration config = null; 

    private DataSource ds = null;

    public DefaultInitDataBaseImpl() {

    }

    public DefaultInitDataBaseImpl(Configuration config,DataSource ds) {
        this.ds = ds;
        this.config = config;
    }
    /* (non-Javadoc)
     * @see com.iqiyi.dbagent.base.i.IInitDataBase#showTables(java.util.List)
     */
    public Map<String,Boolean> showTables(Set<String> tabNames) {
       Map<String,Boolean> tabMap = new ConcurrentHashMap<String,Boolean>();
       for(String tbName:tabNames){
           if(showTable(tbName)){
               tabMap.put(tbName, true);
           }else{
               tabMap.put(tbName, false);
           }
       }
        return tabMap;
    }

    /* (non-Javadoc)
     * @see com.iqiyi.dbagent.base.i.IInitDataBase#createTables(java.util.List)
     */
    public Map<String,Boolean> createTables(Set<String> tabNames) {
        // TODO Auto-generated method stub
        return null;
    }

    /* (non-Javadoc)
     * @see com.iqiyi.dbagent.base.i.IInitDataBase#showTable(java.lang.String)
     */
    public boolean showTable(String tabName) {
        try {
            Connection conn = ds.getConnection();
            String showTabSql = "SHOW TABLES LIKE '" + tabName + "';";
            PreparedStatement pst = conn.prepareStatement(showTabSql);
            ResultSet rs = pst.executeQuery();
            if (rs.first()) {
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    /* (non-Javadoc)
     * @see com.iqiyi.dbagent.base.i.IInitDataBase#createTable(java.lang.String)
     */
    public boolean createTable(String tabNames) {
        // TODO Auto-generated method stub
        return false;
    }

    /* (non-Javadoc)
     * @see com.iqiyi.dbagent.base.i.IInitDataBase#initDataBases(java.util.List)
     */
    public Map<String,Boolean> initDataBase(Set<String> sqls,Connection conn) {
        
        return null;
    }

    /* (non-Javadoc)
     * @see com.iqiyi.dbagent.base.i.IInitDataBase#initDataBase(com.iqiyi.dbagent.base.config.i.Configuration)
     */
    public boolean initDataBase(Configuration config) {
        
        return false;
    }

}
